use std::collections::HashMap;

pub struct Solution;

impl Solution {
    pub fn find_shortest_sub_array(nums: Vec<i32>) -> i32 {
        let mut map = HashMap::new();
        for i in 0..nums.len() {
            map.entry(nums[i]).or_insert(vec![]).push(i);
        }
        let mut vec1 = map.values().collect::<Vec<&Vec<usize>>>();
        vec1.sort_by(|&v1, &v2| {
            v2.len().cmp(&v1.len()).then_with(|| {
                let op1 = v1.first().and_then(|&x| v1.last().map(|&y| y - x));
                let op2 = v2.first().and_then(|&x| v2.last().map(|&y| y - x));
                op1.cmp(&op2)
            })
        });

        vec1.first()
            .and_then(|&v| v.first().and_then(|&first| v.last().map(|&last| last - first + 1)))
            .unwrap_or(0) as i32
    }
}